package cn.yuan.org.controller;

import cn.yuan.basic.Exception.BusinessException;
import cn.yuan.basic.util.PageList;
import cn.yuan.org.domain.Shop;
import cn.yuan.org.query.ShopQuery;
import cn.yuan.org.service.IShopService;
import cn.yuan.util.AjaxResult.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shop")
@Api(tags = "店铺接口",description = "店铺接口详细描述")
public class ShopController {
    @Autowired
    private IShopService shopService;

    @GetMapping("/{id}")
    @ApiOperation(value = "店铺查找",notes = "根据ID查找店铺")
    public Shop loadById(@PathVariable("id")Long id){
        return shopService.loadById(id);
    }

    @GetMapping
    @ApiOperation(value = "查询所有店铺",notes = "根据ID查找店铺")
    public List<Shop> findAll(){
        return shopService.loadAll();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除店铺",notes = "根据ID删除店铺")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            shopService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败");
        }
    }

    @PatchMapping
    @ApiOperation(value = "批量删除店铺",notes = "根据ID删除店铺")
    public AjaxResult batchDel(@RequestBody Long[] ids){
        System.out.println(ids);
        try {
            shopService.batchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败");
        }
    }

    @PutMapping
    @ApiOperation(value = "添加或者修改店铺",notes = "添加或者修改店铺")
    public AjaxResult addOrUpdate(@RequestBody Shop shop){
        try {
            if(shop.getId()==null){
                shopService.save(shop);
            }else {
                shopService.update(shop);
            }
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("操作失败");
        }
    }

    @PostMapping
    @ApiOperation(value = "查询分页",notes = "分页查询店铺")
    public PageList<Shop> queryForPage(@RequestBody ShopQuery shopQuery){
        return shopService.queryForPage(shopQuery);
    }

    @PostMapping("/settlement")
    public AjaxResult settlement(@RequestBody Shop shop){
        try {
            shopService.settlement(shop);
            return AjaxResult.me();
        }catch (BusinessException e){
            return AjaxResult.me().setMsg("入驻失败!"+e.getMessage());//后面这个Message是自定义异常里的
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMsg("系统异常"+e.getMessage());//后面这个Message是自定义异常里的
        }
    }
}
